#!/bin/bash

set -x

set -eo pipefail

# If WordPress has not been installed yet, unpack it.

if [ ! -f wp-config-sample.php ]; then
    tar --strip-components=1 -xzf /opt/app-root/downloads/wordpress.tar.gz

    # Edit the wp-config-sample.php to allow plugins and themes to be
    # installed directly into file system.

    sed -i "/'DB_COLLATE', *'');/a\
    define('FS_METHOD', 'direct');" wp-config-sample.php

    # Edit the wp-config-sample.php to force use of a secure connection
    # for login and adminstration.

    sed -i "/'DB_COLLATE', *'');/a\
    define( 'FORCE_SSL_ADMIN', true );" wp-config-sample.php

    # Edit the wp-config-sample.php to ensure that static files are served
    # up over same protocol as request to avoid mixed content errors.

    sed -i "/'DB_COLLATE', *'');/a\
    if (strpos(\$_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false) \$_SERVER['HTTPS']='on';" wp-config-sample.php
fi

# Check whether the wp-config.php file has been generated previously. If
# not then we need to generate it. This is placed in the persistent volume.

secret() {
    python -c 'import random; import string; print("".join([random.SystemRandom().choice(string.ascii_letters+string.digits) for i in range(50)]))'
}

if [ ! -f wp-config.php ]; then
    TMPCONFIG=/tmp/wp-config-temp.php
    cp wp-config-sample.php $TMPCONFIG

    sed -i "s/'DB_NAME', *'database_name_here'/'DB_NAME', '$MYSQL_DATABASE'/" $TMPCONFIG
    sed -i "s/'DB_USER', *'username_here'/'DB_USER', '$MYSQL_USER'/" $TMPCONFIG
    sed -i "s/'DB_PASSWORD', *'password_here'/'DB_PASSWORD', '$MYSQL_PASSWORD'/" $TMPCONFIG
    sed -i "s/'DB_HOST', *'localhost'/'DB_HOST', '$MYSQL_HOST'/" $TMPCONFIG
    sed -i "s/\$table_prefix *= *'wp_';/\$table_prefix = '$MYSQL_TABLE_PREFIX';/" $TMPCONFIG

    sed -i "s/'AUTH_KEY', *'put your unique phrase here'/'AUTH_KEY', '`secret`'/" $TMPCONFIG
    sed -i "s/'SECURE_AUTH_KEY', *'put your unique phrase here'/'SECURE_AUTH_KEY', '`secret`'/" $TMPCONFIG
    sed -i "s/'LOGGED_IN_KEY', *'put your unique phrase here'/'LOGGED_IN_KEY', '`secret`'/" $TMPCONFIG
    sed -i "s/'NONCE_KEY', *'put your unique phrase here'/'NONCE_KEY', '`secret`'/" $TMPCONFIG
    sed -i "s/'AUTH_SALT', *'put your unique phrase here'/'AUTH_SALT', '`secret`'/" $TMPCONFIG
    sed -i "s/'SECURE_AUTH_SALT', *'put your unique phrase here'/'SECURE_AUTH_SALT', '`secret`'/" $TMPCONFIG
    sed -i "s/'LOGGED_IN_SALT', *'put your unique phrase here'/'LOGGED_IN_SALT', '`secret`'/" $TMPCONFIG
    sed -i "s/'NONCE_SALT', *'put your unique phrase here'/'NONCE_SALT', '`secret`'/" $TMPCONFIG

    mv $TMPCONFIG wp-config.php
fi

# Copy user provided plugins, themes, language files and configuration
# files into the persistent volume. This happens every time the image is
# started, which is not ideal. If application is scaled, then could also
# occur from multple replicas at the same time. No obvious way to avoid
# that, so outstanding question as to whether that will cause any issues.

if [ -d /opt/app-root/downloads/plugins ]; then
    cp -rf /opt/app-root/downloads/plugins/* wp-content/plugins/ 2>/dev/null || true
fi

if [ -d /opt/app-root/downloads/themes ]; then
    cp -rf /opt/app-root/downloads/themes/* wp-content/themes/ 2>/dev/null || true
fi

if [ -d /opt/app-root/downloads/languages ]; then
    cp -rf /opt/app-root/downloads/languages/* wp-content/languages/ 2>/dev/null || true
fi

if [ -f /opt/app-root/downloads/configs/wp-config.php ]; then
    cp -f /opt/app-root/downloads/configs/wp-config.php wp-config.php
fi

if [ -f /opt/app-root/downloads/configs/.htaccess ]; then
    cp -f /opt/app-root/downloads/configs/.htaccess .htaccess
fi

# Enable WebDav access if authentication realm set and user database exists.

if [ x"$WEBDAV_AUTHENTICATION_REALM" != x"" ]; then
    if [ -f /opt/app-root/secrets/webdav/.htdigest ]; then
        cat > /opt/app-root/etc/conf.d/90-webdav.conf << !
<IfModule !dav_module>
LoadModule dav_module modules/mod_dav.so'
</IfModule>

<IfModule !dav_fs_module>
LoadModule dav_fs_module modules/mod_dav_fs.so'
</IfModule>

<IfModule !auth_digest_module>
LoadModule auth_digest_module modules/mod_auth_digest.so'
</IfModule>

<IfModule !authn_file_module>
LoadModule authn_file_module modules/mod_authn_file.so'
</IfModule>

<IfModule !authz_user_module>
LoadModule authz_user_module modules/mod_authz_user.so'
</IfModule>

DavLockDB /opt/app-root/DavLock

Alias /webdav/ /opt/app-root/src/

<Location /webdav/>
    DAV on

    ForceType text/plain
    DirectoryIndex disabled

    AuthType Digest
    AuthName "$WEBDAV_AUTHENTICATION_REALM"
    AuthDigestDomain /webdav/
    AuthDigestProvider file
    AuthUserFile /opt/app-root/secrets/webdav/.htdigest

    Require valid-user
</Location>
!
    fi
fi

# Execute the original run script, replacing this script as current process.

exec /usr/libexec/s2i/run
